<template>
  <div style="width: 100%;height: 100%;">
    <!-- 测试用例表格 -->
    <div v-loading="loading">
      <!-- 上传测试用例 -->
      <!-- <div v-if="isUserAuthId == '111' || isUserAuthId == '666'"> -->
      <div v-if="isUserAuthId == '111' || isUserAuthId == '666'">
        <el-upload ref="uploadCase" class="upload-demo" action="#" multiple="true" v-model:file-list="caseFileText"
          :before-upload="handleBeforeUpload">
          <template #trigger>
            <el-button type="primary">上传用例</el-button>
          </template>
        </el-upload>
      </div>
      <!-- 测试用例表格 -->
      <el-table style="width: 100%;" min-height="400px" max-height="630px" :data="allCaseList" border fit="false">
        <el-table-column fixed type="index" label="序号" width="60" align="center" />
        <el-table-column label="用例名称" min-width="200" header-align="center" property="caseName" show-overflow-tooltip
          fixed="left" border>
          <template #="{ row }">
            <span class="cell-ellipsis">{{ row.caseName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用例编写人" width="100" align="center" property="caseEditMembers"></el-table-column>
        <el-table-column label="更新时间" width="160" align="center" property="caseEditDate" sortable show-overflow-tooltip>
          <template #="{ row }">
            {{ formatDateTime(row.caseEditDate) }}
          </template>
        </el-table-column>
        <el-table-column label="用例得分" width="100" align="center" property="caseScore"></el-table-column>
        <el-table-column label="是否能复用" width="100" align="center" property="isCaseReuse">
          <template #="{ row }">
            <span :style="{ color: row.isCaseReuse == '否' ? 'red' : 'green' }">{{ row.isCaseReuse }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否是补充用例" width="100" align="center" property="isCaseAdd">
          <template #="{ row }">
            <span :style="{ color: row.isCaseAdd == '否' ? 'red' : 'green' }">{{ row.isCaseAdd }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用例质量" width="100" align="center" property="caseQuality">
          <template #="{ row }">
            <span :style="{ color: getQualityColor(row.caseQuality) }">{{
              row.caseQuality === 3
                ? "优"
                : row.caseQuality === 2
                  ? "良"
                  : "差"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="100" align="center" property="isAudit">
          <template #="{ row }">
            <span :style="{ color: row.isAudit == 0 ? 'red' : 'green' }">{{
              row.isAudit === 0 ? "未审核" : "已审核"
            }}</span>
          </template>
        </el-table-column>

        <!-- 操作区域 -->
        <el-table-column label="操作" width="150px" align="center" fixed="right" border>
          <template #="{ row }">
            <div style="width: 100%; display: flex; flex-direction: row; justify-content: center;">
              <!-- 审核 -->
              <el-button type="primary" size="small" plain @click="handleOpenAuditCase(row)">
                <el-icon>
                  <SetUp />
                </el-icon>
              </el-button>
              <!-- 修改 -->
              <el-button v-if="isUserAuthId === '111'" id="addBtn" type="primary" size="small" plain
                @click="handleOpenEditCase(row)">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <!-- 删除 -->
              <el-popconfirm v-if="isUserAuthId === '111' || isUserAuthId === '666'" title="确定要删除该需求吗？"
                @confirm="handleDelTest(row.ID)" @cancel="handleCancelDel">
                <template #reference>
                  <el-button type="danger" size="small" plain>
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核用例弹窗 -->
    <el-dialog v-model="dialogAuditCaseVisible" :show-close="true" :close-on-click-modal="false" title="审核用例">
      <!-- 用例详情 -->
      <ul class="case-info-wrap">
        <li class="case-info-item">
          <p class="case-info-title">用例名称：</p>
          <p class="case-info-text">{{ isRequirementCase.caseName }}</p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">操作步骤：</p>
          <p class="case-info-text" v-html="isRequirementCase.operationSteps ? isRequirementCase.operationSteps : '暂无'">
          </p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">预期结果：</p>
          <p class="case-info-text" v-html="isRequirementCase.expectedResult ? isRequirementCase.expectedResult : '暂无'">
          </p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">实际结果：</p>
          <p class="case-info-text" v-html="isRequirementCase.realResult ? isRequirementCase.realResult : '暂无'"></p>
        </li>
      </ul>
      <!-- 审核用例 -->
      <el-form ref="auditFormRef" :model="auditFormData" v-if="isUserAuthId === '111'">
        <el-form-item label="用例质量:">
          <el-radio-group v-model="auditFormData.caseQuality">
            <el-radio :value="3">优</el-radio>
            <el-radio :value="2">良</el-radio>
            <el-radio :value="1">差</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用例得分:">
          <el-input-number v-model="auditFormData.caseScore" :min="0" size="small" />
        </el-form-item>
        <el-form-item label="是否能复用：">
          <el-switch v-model="auditFormData.isCaseReuse" inline-prompt active-value="是" inactive-value="否" />
        </el-form-item>
        <el-form-item label="是否是补充用例：">
          <el-switch v-model="auditFormData.isCaseAdd" inline-prompt active-value="是" inactive-value="否" />
        </el-form-item>
      </el-form>

      <template #footer v-if="isUserAuthId == '111'">
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="submitAuditFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改用例弹窗 -->
    <el-dialog title="用例详情" v-model="dialogEditCaseVisible" :show-close="true" :close-on-click-modal="false">
      <el-form ref="caseDlgFormRef" v-model="isRequirementCase">
        <el-form-item label="用例名称:">
          <el-input type="text" v-model="isRequirementCase.caseName" placeholder="请输入用例名称" />
        </el-form-item>
        <el-form-item label="操作步骤:">
          <el-input type="textarea" :rows="5" v-model="isRequirementCase.operationSteps" placeholder="请输入操作步骤">
          </el-input>
        </el-form-item>
        <el-form-item label="预期结果:">
          <el-input type="textarea" :rows="5" v-model="isRequirementCase.expectedResult" placeholder="请输入预期结果" />
        </el-form-item>
        <el-form-item label="实际结果:">
          <el-input type="textarea" :rows="5" v-model="isRequirementCase.realResult" placeholder="请输入实际结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="submitEditFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, PropType, watch } from "vue";
import {
  getRequirementCase,
  postUploadCaseFile,
  postRequirementCase,
  delCaseByid,
  postAuditCaseByid,
  putEditeCaseByid,
} from "@/api/project/index";
import { ElMessage } from "element-plus";
import {
  formatDateTime
} from "@/utils/utils";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  id: {
    type: Number as PropType<number | null>,
    required: true
  },
  itemItemId: {
    type: Number as PropType<number | null>,
    required: false
  },

});

const emit = defineEmits(['case-result']);

//* 变量声明
const loading = ref(false);
const isUserAuthId = ref<any>();// 当前用户权限
const isRequirementID = ref<any>(null);// 当前需求ID
const isRequirementItemId = ref<any>(null);

const dialogAuditCaseVisible = ref(false);// 审核用例弹窗
const isRequirementCase = ref<any>(null);// 当前用例信息
const dialogEditCaseVisible = ref(false);// 修改用例弹窗

const allCaseList = ref<any>([]);// 所有测试用例数据
const caseFileText = ref<any>([]);// 测试用例文件

// 定义不同用例质量的颜色
const getQualityColor = (quality: number) => {
  switch (quality) {
    case 3:
      return "green"; // 优 - 绿色
    case 2:
      return "blue"; // 良 - 蓝色
    default:
      return "red"; // 差 - 红色
  }
};

// 审核用例提交数据
const auditFormData = ref({
  id: null,
  caseQuality: 3,
  caseScore: 100,
  isCaseReuse: "否",
  isCaseAdd: "否",
  isAudit: 1,
});

// 修改用例提交数据
const editFormData = ref({
  id: null,
  caseName: "",
  operationSteps: "",
  expectedResult: "",
  realResult: "",
});

// 监听 id 的变化，获取数据
watch(() => props.id, async (newId) => {
  if (newId) {
    isRequirementID.value = newId;
  }
}, { immediate: true });

// 监听 itemItemId 的变化，获取数据
watch(() => props.itemItemId, async (newId) => {
  if (newId) {
    isRequirementItemId.value = newId;
  }
}, { immediate: true });



// TODO 获取测试用例
const getAllCaseList = async () => {
  loading.value = true;
  const { data } = await getRequirementCase({
    id: isRequirementID.value,
    page: 1,
    pageSize: 100000000
  });

  if (data.code === 200) {
    allCaseList.value = data.data.list;
    if (data.data.list.length === 0) {
      emit('case-result', false);
    } else {
      emit('case-result', true);
    }

    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    throw console.error(data.msg);
  };

  loading.value = false;
};

// TODO 上传测试用例
const handleBeforeUpload = async (file: any) => {
  const { data } = await postUploadCaseFile(file);
  if (data.code === 200) {
    // 导入测试用例
    const resData = await postRequirementCase({
      requirementId: isRequirementID.value,
      itemItemId: isRequirementItemId.value,
      filePath: data.data.resultFilePath
    });

    if (resData.data.code === 200) {
      ElMessage.success(resData.data.msg);
      loading.value = true;
      await getAllCaseList();
      loading.value = false;
    } else {
      // 导入失败提示
      ElMessage.error(resData.data.msg);
      throw Error(resData.data.msg);
    }
  } else {
    // 上传用例失败提示
    ElMessage.error(data.msg);
    throw Error(data.msg);
  }
  return false;
};

// TODO 取消删除需求
const handleCancelDel = () => {
  ElMessage.info("取消删除！");
  return;
};

// TODO 确认删除用例
const handleDelTest = async (id: number) => {
  const { data } = await delCaseByid(id);
  if (data.code === 200) {
    ElMessage.success(data.msg);
    loading.value = true;
    await getAllCaseList();
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    throw new Error(data.msg);
  }
};

// TODO 关闭弹窗
const handleCloseDialog = () => {
  auditFormData.value = {
    id: null,
    caseQuality: 3,
    caseScore: 100,
    isCaseReuse: "否",
    isCaseAdd: "否",
    isAudit: 1,
  };

  editFormData.value = {
    id: null,
    caseName: "",
    operationSteps: "",
    expectedResult: "",
    realResult: "",
  };

  dialogAuditCaseVisible.value = false;
  dialogEditCaseVisible.value = false;
};

// TODO 开启审核用例弹窗
const handleOpenAuditCase = (row: any) => {
  isRequirementCase.value = row;
  auditFormData.value = {
    id: row.ID,
    caseQuality: row.caseQuality,
    caseScore: row.caseScore,
    isCaseReuse: row.isCaseReuse,
    isCaseAdd: row.isCaseAdd,
    isAudit: 1,
  };
  dialogAuditCaseVisible.value = true;
};

// TODO 提交审核用例数据
const submitAuditFormData = async () => {
  const { data } = await postAuditCaseByid(auditFormData.value);

  if (data.code === 200) {
    ElMessage.success(data.msg);
    dialogAuditCaseVisible.value = false;

    loading.value = true;
    await getAllCaseList();
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    dialogAuditCaseVisible.value = false;
    throw console.error(data.msg);
  }
};

// TODO 开启修改用例弹窗
const handleOpenEditCase = (row: any) => {
  editFormData.value = {
    id: row.ID,
    caseName: row.caseName,
    operationSteps: row.operationSteps,
    expectedResult: row.expectedResult,
    realResult: row.realResult
  };
  dialogEditCaseVisible.value = true;
};

// TODO 提交修改用例数据
const submitEditFormData = async () => {
  const { data } = await putEditeCaseByid(editFormData.value);

  if (data.code === 200) {
    ElMessage.success(data.msg);
    dialogEditCaseVisible.value = false;
    loading.value = true;
    await getAllCaseList();
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    dialogEditCaseVisible.value = false;
    throw console.error(data.msg);
  }
};


onMounted(() => {
  getAllCaseList();
});
</script>

<style scoped lang="scss">
// 文本溢出省略
.cell-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 快捷筛选
.card-wrap-count-search {
  display: inline-block;
  padding: 5px;
  margin-right: 10px;
  background-color: #f2f3f5;
  border-radius: 2px;
  cursor: pointer;
}

.card-wrap-count-search:hover {
  background-color: #a0cfff;
}

// 操作按钮
.table-operation {
  width: 36px;
  height: 26px;
  padding: 0 10px;
  display: inline-block;
  color: #409eff;
}

.table-operation-view:hover,
.table-operation-edit:hover {
  background-color: #409eff;
  color: white;
}

.table-operation-del:hover {
  background-color: #ff343f;
  color: white;
}

/* 添加需求弹窗 */
.el-dialog {
  --el-dialog-margin-top: 20px;

  .dialog-form {
    .el-form-item {
      padding-left: 5px;
    }
  }
}

/* 查看需求 */
.dialog-view-requireTitle {
  font-weight: bold;
}

.el-row {
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  text-align: left;
}

.el-col {
  border: 1px solid #eee;
  padding: 10px 0;
}

/* 用例总览区域 */
.case-item {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  color: #303133;

  p {
    background-color: #f2f3f5;
    border-radius: 2px;
    padding: 5px 10px;
  }
}

/* 审核用例详情 */
.case-info-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;

  .case-info-item {
    width: 100%;
    display: flex;
    justify-content: left;

    .case-info-title {
      width: 70px;
      margin-bottom: 20px;
      line-height: 150%;
      font-weight: bold;
    }

    .case-info-text {
      width: calc(100% - 70px);
      line-height: 150%;
      margin-bottom: 20px;
      border: 1px solid #ddd;
      padding: 10px;
      border-radius: 5px;
    }
  }
}
</style>

<style lang="scss">
.is-dark {
  width: 200px;
  opacity: 0.8;
}

.el-table {
  --el-table-row-hover-bg-color: #d9ecff;
}

.el-dialog {
  --el-dialog-margin-top: 50px;
}

.el-dialog__body {
  padding: 10px 20px 0px;
}
</style>
